import { Component, ElementRef, HostBinding, OnDestroy } from '@angular/core';
import { IHeaderParams } from '@ag-grid-enterprise/all-modules';
import { IHeaderAngularComp } from '@ag-grid-community/angular';
import { ExpressionService } from '@core/services/expression/ExpressionService';

interface MyParams extends IHeaderParams {
  menuIcon: string;
}

@Component({
  templateUrl: 'custom-header.component.html',
  styleUrls: ['custom-header.component.scss'],
})
export class CustomHeaderComponent implements OnDestroy, IHeaderAngularComp {
  public params: MyParams;
  public sorted: string;
  public strTip: string;
  private elementRef: ElementRef;
  @HostBinding('style.text-align') align: string;
  @HostBinding('style.width') width: string;

  constructor(
    elementRef: ElementRef,
    protected expressionService: ExpressionService,
  ) {
    this.elementRef = elementRef;
    this.align = 'left';
    this.width = '100%';
  }

  agInit(params: MyParams): void {
    this.params = params;
    this.strTip = this.params.column['colDef'].headerTooltipFormatter ? this.params.column['colDef'].headerTooltipFormatter : this.params.column['colDef'].tooltipFormatter;
  }

  ngOnDestroy() {
    // console.log(`Destroying HeaderComponent`);
  }

  onMenuClick() {
    this.params.showColumnMenu(this.querySelector('.customHeaderMenuButton'));
  }

  onSortRequested(order, event) {
    this.params.setSort(order, event.shiftKey);
  };

  onSortChanged() {
    if (this.params.column.isSortAscending()) {
      this.sorted = 'asc';
    } else if (this.params.column.isSortDescending()) {
      this.sorted = 'desc';
    } else {
      this.sorted = '';
    }
  };

  private querySelector(selector: string) {
    return <HTMLElement>this.elementRef.nativeElement.querySelector(
      '.customHeaderMenuButton', selector);
  }

  refresh(params): boolean {
    return true;
  }

  showLabel(params) {
    let labelFormatter = params.column['colDef'].labelFormatter ? params.column['colDef'].labelFormatter : params.column['colDef'].labelFormatter;
    let show
    if(!labelFormatter) {
      show = params.displayName;
    } else {
      show = this.expressionService.eval(labelFormatter, {
        context: params.context,
        model: params.context.model,
        value: params.displayName
      });
    }
    if(!show) show = params.displayName;
    return show;
  }
}
